package guru.kafka.zookeeper.test;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * Created by xufei on 16/11/3.
 */
public class FireLeaderElection {


    public static void main(String[] args) throws KeeperException, InterruptedException {

        ZooKeeper zk = null;

        while (zk == null) {
            try {
                zk = new ZooKeeper("localhost:2181,localhost:2182,localhost:2183", 50000, new Watcher() {
                    public void process(WatchedEvent watchedEvent) {
                        if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        createNode(zk);




        Thread.sleep(1000000L);

    }

    private static void createNode(final ZooKeeper zk) throws KeeperException, InterruptedException {
        Stat stat = zk.exists("/lroot", true);

        if (stat == null) {
            zk.create("/lroot", "1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        final String path = zk.create("/lroot/n_", "1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println(path);
        int idx = Integer.valueOf(path.substring("/lroot/n_".length()));

        zk.exists("/lroot/n_" + getPreKey(idx), new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
                    System.out.println(path + "自己为leader");
                }
                if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                    System.out.println(path + "失败");
                }
            }
        });
    }

    private static String getPreKey(int idx) {
        int preIdx = idx - 1;
        String preIdxStr = String.valueOf(preIdx);
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < (10 - preIdxStr.length()); i++) {
            strBuilder.append("0");
        }
        strBuilder.append(preIdxStr);
        return strBuilder.toString();
    }
}
